<!-- 预约管理 -->
<template>
  <PageContainer title="预约管理">
    <!-- 搜索和操作区 -->
    <div class="search-operate">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="searchForm.keyword" placeholder="请输入患者姓名/宠物名称搜索" prefix-icon="el-icon-search"
            class="search-input"></el-input>
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.status" placeholder="请选择预约状态" class="status-select">
            <el-option label="全部" value=""></el-option>
            <el-option label="待确认" value="pending"></el-option>
            <el-option label="已确认" value="confirmed"></el-option>
            <el-option label="已完成" value="completed"></el-option>
            <el-option label="已取消" value="cancelled"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" class="date-picker"></el-date-picker>
        </el-col>
        <el-col :span="4" class="operate-buttons">
          <el-button type="primary" @click="handleRefresh">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 预约统计卡片 -->
    <div class="appointment-stats" style="margin-top: 20px;">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-header">
              <i class="el-icon-calendar stat-icon"></i>
              <h4>今日预约数</h4>
            </div>
            <div class="stat-value">{{ todayAppointmentCount }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-header">
              <i class="el-icon-s-flag stat-icon"></i>
              <h4>待确认数</h4>
            </div>
            <div class="stat-value">{{ pendingAppointmentCount }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-header">
              <i class="el-icon-check stat-icon"></i>
              <h4>本月完成数</h4>
            </div>
            <div class="stat-value">{{ monthCompletedCount }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-header">
              <i class="el-icon-close stat-icon"></i>
              <h4>取消率</h4>
            </div>
            <div class="stat-value">{{ cancelRate }}%</div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 预约列表表格 -->
    <el-table :data="appointmentList" border stripe :loading="loading" style="width: 100%; margin-top: 20px;"
      @row-click="handleRowClick">
      <el-table-column label="预约ID" prop="id" width="100" align="center"></el-table-column>
      <el-table-column label="患者姓名" prop="patientName" width="120" align="center"></el-table-column>
      <el-table-column label="宠物名称" prop="petName" width="120" align="center"></el-table-column>
      <el-table-column label="宠物类型" prop="petType" width="120" align="center"></el-table-column>
      <el-table-column label="预约类型" width="120" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.appointmentType === 'offline' ? 'primary' : 'info'">
            {{ scope.row.appointmentType === 'offline' ? '线下就诊' : '线上问诊' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" prop="appointmentTime" width="180" align="center"></el-table-column>
      <el-table-column label="预约状态" width="120" align="center">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="提交时间" prop="createTime" width="180" align="center"></el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button type="text" @click="handleViewDetail(scope.row, $event)">详情</el-button>
          <el-button type="text" v-if="scope.row.status === 'pending'"
            @click="handleConfirmAppointment(scope.row, $event)" style="color: #67c23a;">
            确认
          </el-button>
          <el-button type="text" v-if="scope.row.status === 'pending' || scope.row.status === 'confirmed'"
            @click="handleCancelAppointment(scope.row, $event)" style="color: #f56c6c;">
            取消
          </el-button>
          <el-button type="text" v-if="scope.row.status === 'confirmed'"
            @click="handleCompleteAppointment(scope.row, $event)" style="color: #409eff;">
            完成
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <TablePagination :total="total" :page-size="pageSize" :current-page="currentPage" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" style="margin-top: 20px; text-align: right;"></TablePagination>

    <!-- 预约详情弹窗 -->
    <el-dialog title="预约详情" :visible.sync="detailVisible" width="800px" :before-close="handleDetailClose">
      <div class="appointment-detail">
        <div class="detail-header">
          <div class="header-left">
            <h3>预约ID：{{ currentAppointment.id }}</h3>
            <el-tag :type="getStatusTagType(currentAppointment.status)">
              {{ getStatusLabel(currentAppointment.status) }}
            </el-tag>
          </div>
          <div class="header-right">
            <p>提交时间：{{ currentAppointment.createTime }}</p>
            <p>确认时间：{{ currentAppointment.confirmTime || '未确认' }}</p>
            <p>完成时间：{{ currentAppointment.completeTime || '未完成' }}</p>
            <p>取消时间：{{ currentAppointment.cancelTime || '未取消' }}</p>
          </div>
        </div>

        <div class="detail-section">
          <h4>患者信息</h4>
          <el-table :data="[currentAppointment.patientInfo]" border style="width: 100%;">
            <el-table-column label="患者姓名" prop="patientName" width="150" align="center"></el-table-column>
            <el-table-column label="联系电话" prop="phone" width="150" align="center"></el-table-column>
            <el-table-column label="所在地区" prop="region" width="150" align="center"></el-table-column>
            <el-table-column label="备注" prop="remark"></el-table-column>
          </el-table>
        </div>

        <div class="detail-section">
          <h4>宠物信息</h4>
          <el-table :data="[currentAppointment.petInfo]" border style="width: 100%;">
            <el-table-column label="宠物名称" prop="petName" width="120" align="center"></el-table-column>
            <el-table-column label="宠物类型" prop="petType" width="120" align="center"></el-table-column>
            <el-table-column label="宠物年龄" prop="petAge" width="120" align="center"></el-table-column>
            <el-table-column label="宠物品种" prop="petBreed" width="150" align="center"></el-table-column>
            <el-table-column label="宠物症状" prop="symptom"></el-table-column>
          </el-table>
        </div>

        <div class="detail-section">
          <h4>预约信息</h4>
          <el-table :data="[currentAppointment.appointmentInfo]" border style="width: 100%;">
            <el-table-column label="预约类型" prop="appointmentType" width="150" align="center">
              <template #default="scope">
                {{ scope.row.appointmentType === 'offline' ? '线下就诊' : '线上问诊' }}
              </template>
            </el-table-column>
            <el-table-column label="预约时间" prop="appointmentTime" width="180" align="center"></el-table-column>
            <el-table-column label="就诊地址" prop="clinicAddress" width="200" align="center"
              v-if="currentAppointment.appointmentType === 'offline'"></el-table-column>
            <el-table-column label="预约备注" prop="appointmentRemark"></el-table-column>
          </el-table>
        </div>

        <div class="detail-section" v-if="currentAppointment.status === 'completed'">
          <h4>就诊结论</h4>
          <div class="conclusion-content">
            <p>{{ currentAppointment.conclusion || '无' }}</p>
          </div>
        </div>

        <div class="detail-section" v-if="currentAppointment.status === 'cancelled'">
          <h4>取消原因</h4>
          <div class="cancel-reason">
            <p>{{ currentAppointment.cancelReason || '无' }}</p>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 完成预约弹窗 -->
    <el-dialog title="完成预约" :visible.sync="completeVisible" width="500px">
      <el-form :model="completeForm" :rules="completeRules" ref="completeFormRef" label-width="100px">
        <el-form-item label="就诊结论" prop="conclusion">
          <el-input v-model="completeForm.conclusion" type="textarea" :rows="5" placeholder="请输入就诊结论..."></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="completeVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCompleteSubmit">确认提交</el-button>
      </template>
    </el-dialog>

    <!-- 取消预约弹窗 -->
    <el-dialog title="取消预约" :visible.sync="cancelVisible" width="500px">
      <el-form :model="cancelForm" :rules="cancelRules" ref="cancelFormRef" label-width="100px">
        <el-form-item label="取消原因" prop="cancelReason">
          <el-input v-model="cancelForm.cancelReason" type="textarea" :rows="3" placeholder="请输入取消原因..."></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCancelSubmit">确认取消</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageContainer from '@/components/common/PageContainer.vue'
import TablePagination from '@/components/common/TablePagination.vue'
import { getAppointmentList, getAppointmentDetail, confirmAppointment, cancelAppointment, completeAppointment } from '@/api/doctor'

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  dateRange: []
})

// 表格数据
const appointmentList = ref([])
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const loading = ref(false)

// 统计数据
const todayAppointmentCount = ref(0)
const pendingAppointmentCount = ref(0)
const monthCompletedCount = ref(0)
const cancelRate = ref(0)

// 弹窗相关
const detailVisible = ref(false)
const completeVisible = ref(false)
const cancelVisible = ref(false)
const currentAppointment = ref({})

// 完成预约表单
const completeForm = reactive({
  appointmentId: '',
  conclusion: ''
})

// 完成预约表单校验规则
const completeRules = reactive({
  conclusion: [
    { required: true, message: '请输入就诊结论', trigger: 'blur' },
    { min: 20, message: '结论长度不能少于20字', trigger: 'blur' }
  ]
})

// 取消预约表单
const cancelForm = reactive({
  appointmentId: '',
  cancelReason: ''
})

// 取消预约表单校验规则
const cancelRules = reactive({
  cancelReason: [
    { required: true, message: '请输入取消原因', trigger: 'blur' },
    { min: 10, message: '原因长度不能少于10字', trigger: 'blur' }
  ]
})

// 表单引用
const completeFormRef = ref(null)
const cancelFormRef = ref(null)

// 预约状态标签类型
const getStatusTagType = (status) => {
  const statusTypeMap = {
    pending: 'warning',
    confirmed: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusTypeMap[status] || 'default'
}

// 预约状态文本
const getStatusLabel = (status) => {
  const statusLabelMap = {
    pending: '待确认',
    confirmed: '已确认',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusLabelMap[status] || '未知状态'
}

// 获取预约列表
const fetchAppointmentList = async () => {
  try {
    loading.value = true
    const [startDate, endDate] = searchForm.dateRange || []
    const res = await getAppointmentList({
      keyword: searchForm.keyword,
      status: searchForm.status,
      startDate,
      endDate,
      doctorId: localStorage.getItem('doctorId'), // 医生只能查看自己的预约
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    appointmentList.value = res.data.list
    total.value = res.data.total
    // 更新统计数据
    todayAppointmentCount.value = res.data.stats.todayAppointmentCount
    pendingAppointmentCount.value = res.data.stats.pendingAppointmentCount
    monthCompletedCount.value = res.data.stats.monthCompletedCount
    cancelRate.value = res.data.stats.cancelRate
  } catch (error) {
    ElMessage.error('获取预约列表失败')
  } finally {
    loading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchAppointmentList()
}

// 页码改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchAppointmentList()
}

// 刷新列表
const handleRefresh = () => {
  fetchAppointmentList()
}

// 查看预约详情
const handleViewDetail = async (row, event) => {
  event.stopPropagation()
  await fetchAppointmentDetail(row.id)
}

// 行点击事件（查看详情）
const handleRowClick = async (row) => {
  await fetchAppointmentDetail(row.id)
}

// 获取预约详情
const fetchAppointmentDetail = async (appointmentId) => {
  try {
    loading.value = true
    const res = await getAppointmentDetail(appointmentId)
    currentAppointment.value = res.data
    detailVisible.value = true
  } catch (error) {
    ElMessage.error('获取预约详情失败')
  } finally {
    loading.value = false
  }
}

// 确认预约
const handleConfirmAppointment = async (row, event) => {
  event.stopPropagation()
  try {
    await ElMessageBox.confirm(
      '确定要确认该预约吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    await confirmAppointment(row.id)
    ElMessage.success('确认成功')
    fetchAppointmentList()
  } catch (error) {
    ElMessage.error('确认失败')
  }
}

// 取消预约（打开弹窗）
const handleCancelAppointment = (row, event) => {
  event.stopPropagation()
  cancelForm.appointmentId = row.id
  cancelForm.cancelReason = ''
  cancelVisible.value = true
}

// 提交取消预约
const handleCancelSubmit = async () => {
  try {
    await cancelFormRef.value.validate()
    await cancelAppointment({
      id: cancelForm.appointmentId,
      cancelReason: cancelForm.cancelReason
    })
    ElMessage.success('取消成功')
    cancelVisible.value = false
    detailVisible.value = false
    fetchAppointmentList()
  } catch (error) {
    ElMessage.error('取消失败')
  }
}

// 完成预约（打开弹窗）
const handleCompleteAppointment = (row, event) => {
  event.stopPropagation()
  completeForm.appointmentId = row.id
  completeForm.conclusion = ''
  completeVisible.value = true
}

// 提交就诊结论
const handleCompleteSubmit = async () => {
  try {
    await completeFormRef.value.validate()
    await completeAppointment({
      id: completeForm.appointmentId,
      conclusion: completeForm.conclusion
    })
    ElMessage.success('完成成功')
    completeVisible.value = false
    detailVisible.value = false
    fetchAppointmentList()
  } catch (error) {
    ElMessage.error('完成失败')
  }
}

// 页面挂载时获取数据
onMounted(() => {
  fetchAppointmentList()
})
</script>

<style scoped lang="scss">
.search-operate {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;

  .search-input {
    width: 100%;
  }

  .status-select {
    width: 100%;
  }

  .date-picker {
    width: 100%;
  }

  .operate-buttons {
    display: flex;
    justify-content: flex-end;
  }
}

.appointment-stats {
  .stat-card {
    height: 120px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 15px;

    .stat-header {
      display: flex;
      align-items: center;
      gap: 10px;

      .stat-icon {
        font-size: 20px;
        color: #409eff;
      }

      h4 {
        font-size: 14px;
        color: #666;
        font-weight: normal;
      }
    }

    .stat-value {
      font-size: 24px;
      font-weight: 600;
      color: #333;
    }
  }
}

.appointment-detail {
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e6e6e6;

    .header-left {
      display: flex;
      align-items: center;
      gap: 10px;

      h3 {
        font-size: 16px;
        font-weight: 600;
      }
    }

    .header-right {
      text-align: right;

      p {
        font-size: 14px;
        color: #666;
        margin-bottom: 5px;
      }
    }
  }

  .detail-section {
    margin-bottom: 20px;

    h4 {
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 10px;
      color: #333;
      padding-left: 5px;
      border-left: 3px solid #409eff;
    }
  }

  .conclusion-content,
  .cancel-reason {
    padding: 15px;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    background-color: #f9f9f9;
    line-height: 1.8;
    color: #666;
  }
}

::v-deep .el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
  padding: 20px;
}
</style>